$(function(){
   //覆盖
   $('tbody').html(`
   <tr>
               <th class="desc">项目</th>
               <th class="unit-price">单价</th>
               <th class="num">数量</th>
               <th class="total-price">总价</th>
               <th style="width:40px">操作</th>
             </tr>
   `)
   //请求接口
 $.get('/api/carts/index.jsp',{token},res=>{
   let totalPrice = 0

   //console.log(res.data);
   //遍历&追加
   $.each(res.data,(index,item)=>{
     
     totalPrice+=parseFloat(item.shop_price) *parseInt(item.goods_number)
     let html = `
       <tr data-id="${item.goods_id}">
         <td class="title">
           <a href="./store" data-reactid="${item.store_id}">
             【${item.store_name}】${item.goods_name}
             </a>
           <p>${item.goods_attr}</p>
         </td>
         <td>¥${item.shop_price}</td>
         <td>
           <div class="input-number">
             <button class="minus-btn" type="button">-</button>
             <input type="text" class="input" value="${item.goods_number}" />
             <button class="plus-btn" type="button">+</button>
           </div>
         </td>
         <td>¥${item.shop_price*item.goods_number}</td>
         <td><a href="javascript:;">删除</a></td>
       </tr>
     `
     //追加
     $('tbody').append(html)
   })
   //总价
   $('.total-price b').html(totalPrice)
 },'json') 
 //购物车删除
   //1 事件委托绑定点击事件
   //2 事件处理函数中 获取参数 请求接口
   $('body').on('click','a',function(){
    let goods_id = $(this).parents('tr').attr('data-id')
    $.get('/api/carts/delete.jsp',{token,goods_id},res=>{
     if(res.meta.state === 200){
       window.location.reload()
     }else{
       cocoMessage.error(res.meta.msg);
     }
    },'json')
  })


  //商品加+1
  $('tbody').on('click','.plus-btn',function(){
    let num = $(this).prev().val()
   num++
   let goods_id = $(this).parents('tr').attr('data-id')
    $.post('/api/carts/update.jsp',{token,goods_id,buyNum:num},res=>{
     if(res.meta.state === 200){
      window.location.reload()
    }else{
       // 库存不足
       if (res.meta.msg === "库存不足") {
           // 发送异步请求改成最大库存
           msg = `【${res.data.goods_name}】${res.meta.msg}，剩余库存：${res.data.total_number}`;
         } else {
           msg = res.meta.msg;
         }
      cocoMessage.error(res.meta.msg);
    }
    },'json')
  })


   //商品加-1
   $('tbody').on('click','.minus-btn',function(){
    let num = $(this).next().val()
   num--
   if(num<1){
     cocoMessage.error('至少购买一件商品');
     return
   }
   let goods_id = $(this).parents('tr').attr('data-id')
    $.post('/api/carts/update.jsp',{token,goods_id,buyNum:num},res=>{
     if(res.meta.state === 200){
      location.reload()
    }else{
      cocoMessage.error(res.meta.msg);
    }
    },'json')
  })
})

